import 'package:bai_le_men_im/cmomon/global.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'package:overlay_support/overlay_support.dart';
import '../constants.dart' show AppColors, AppStyles, Constants;
import 'package:async/async.dart';
import 'package:flutter/material.dart';

class SendRedEnvelopePage extends StatefulWidget {
  final String targetId;
  SendRedEnvelopePage({this.targetId});
  @override
  _SendRedEnvelopePageState createState() => _SendRedEnvelopePageState();
}

class _SendRedEnvelopePageState extends State<SendRedEnvelopePage> {
  final AsyncMemoizer _memoizer = AsyncMemoizer();
  String clientId;
  String token;
  Response response;
  Dio dio = new Dio();
  bool isNumVerification = false;
  String _num = '0';
  bool _fetching = false;

  TextEditingController phoneController;
  TextEditingController codeController = TextEditingController();

  getData() {
    return _memoizer.runOnce(() async {
      clientId = await FlutterWildfire.getClientId();
      print('clientId = $clientId');
      token = Global.profile.token;
      print(token);
    });
  }

  initPage() async {
    print('clientId = $clientId');
  }

  verificationPhone() {
    final allText = phoneController.text.trim();
    RegExp exp = new RegExp(r"^\d+$");
    if (exp.hasMatch(allText)) {
      this.setState(() {
        _num = allText;
        isNumVerification = true;
      });
      return true;
    } else {
      this.setState(() {
        _num = allText;
        isNumVerification = false;
      });
      return false;
    }
  }

  @override
  void initState() {
    initPage();
    phoneController = TextEditingController();
    phoneController.addListener(verificationPhone);
    super.initState();
  }

  @override
  void dispose() {
    phoneController.removeListener(verificationPhone);
    phoneController.dispose();
    super.dispose();
  }

  // saveScoreHandler() async {
  //   response = await dio.post('http://chat.digintech.cn:8686/saveUserPoints',
  //       data: {"userId": Global.profile.user.uid, "points": 200},
  //       options:
  //           Options(headers: {"X_Access_Token": token, "clientId": clientId}));
  //   if (response.data['code'] != 0) {
  //     throw response.data['message'];
  //   }
  //   print(response.data.toString());
  // }

  clickSendFromServerHandler() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (_fetching) return;
    int point;
    try {
      point = _num.isEmpty ? 0 : int.parse(_num);
    } catch (e) {
      point = 0;
    }
    if (point <= 0) {
      return;
    }
    _fetching = true;
    try {
      response = await dio.post('http://chat.digintech.cn:8686/pointsTrade',
          data: {
            "formUserId": Global.profile.user.uid,
            "toUserId": widget.targetId,
            "tradePoints": point
          },
          options: Options(
              headers: {"X_Access_Token": token, "clientId": clientId}));
      if (response.data['code'] != 0) {
        throw response.data['message'];
      }
      _fetching = false;
      Navigator.of(context).pop();
      print(response.data.toString());
    } catch (e) {
      toast(e);
      _fetching = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(AppColors.PrimaryColor),
        appBar: AppBar(
          centerTitle: true,
          title: Text('发红包', style: AppStyles.TitleStyle),
          leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(
                  IconData(
                    0xe64c,
                    fontFamily: Constants.IconFontFamily,
                  ),
                  size: Constants.ActionIconSize + 4.0,
                  color: const Color(AppColors.ActionIconColor))),
          elevation: 0.0,
          brightness: Brightness.light,
          backgroundColor: const Color(AppColors.PrimaryColor),
        ),
        body: FutureBuilder(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            return Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    margin: const EdgeInsets.symmetric(
                        horizontal: 18.0, vertical: 10.0),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 18.0, vertical: 5.0),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(4.0)),
                    child: Row(
                      children: <Widget>[
                        Text(
                          '积分',
                          style: TextStyle(fontSize: 18.0),
                        ),
                        Expanded(
                          child: TextField(
                            textAlign: TextAlign.right,
                            // onEditingComplete: getCodeHandler,
                            controller: phoneController,
                            // obscureText: true, // 隐藏输入
                            keyboardType: TextInputType.phone,
                            cursorColor: Colors.green,
                            // maxLength: 11,
                            autofocus: true,
                            decoration: InputDecoration(
                              hintText: '0',
                              enabledBorder: UnderlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Colors.transparent)),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Colors.transparent)),
                              // fillColor: Colors.transparent,
                              // filled: true,
                              // labelText: '手机号',
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 5.0,
                        ),
                        Text(
                          '个',
                          style: TextStyle(fontSize: 18.0),
                        ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 10.0,
                ),
                Text(
                  _num.isEmpty ? '0' : _num,
                  style: TextStyle(fontSize: 45.0, fontWeight: FontWeight.bold),
                ),
                SizedBox(
                  height: 20.0,
                ),
                RaisedButton(
                  color: Colors.deepOrange,
                  textColor: Colors.white,
                  disabledColor: Colors.deepOrange[200],
                  disabledTextColor: Colors.white,
                  padding:
                      EdgeInsets.symmetric(horizontal: 40.0, vertical: 13.0),
                  child: Text(
                    '发积分红包',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  onPressed:
                      isNumVerification ? clickSendFromServerHandler : null,
                ),
              ],
            );
          },
        ));
  }
}
